describe('Frontend-Backend Integration Tests', () => {
  before(() => {
    cy.cleanTestData()
  })

  afterEach(() => {
    cy.cleanTestData()
  })

  describe('完整业务流程集成测试', () => {
    it('应该完成从前端到后端的完整SMT流程', () => {
      cy.fixture('test-data').then((testData) => {
        const { orders, operators, parts } = testData
        
        // 首先验证后端服务可用
        cy.apiRequest('GET', '/actuator/health').then((healthResponse) => {
          if (healthResponse.status !== 200) {
            cy.log('警告: 后端服务可能未启动')
          }
        })
        
        // 开始前端流程
        cy.visit('/')
        cy.waitForPageLoad()
        
        // 导航到选择页面
        cy.get('body').then(($body) => {
          if ($body.find('.menu-item').length > 0) {
            cy.get('.menu-item').first().click()
          } else {
            // 如果直接进入选择页面
            cy.visit('/pages/select/select')
          }
        })
        cy.waitForPageLoad()
        
        // 输入订单号并验证后端响应
        cy.get('input').first().clear().type(orders.valid.fullScanCode)
        cy.get('button, .btn-start').contains('开始').click()
        cy.waitForPageLoad()
        
        // 验证是否成功进入作业员确认页面
        cy.url().should('include', 'operator-confirm')
        
        // 输入作业员ID
        cy.get('input').first().clear().type(operators.valid.operatorId)
        cy.get('button, .btn-start').contains('开始').click()
        cy.waitForPageLoad()
        
        // 验证是否进入物料配送确认页面
        cy.url().should('include', 'delivery-confirm')
        
        // 验证页面显示的订单信息
        cy.get('body').should('contain', orders.valid.orderNo)
        
        // 模拟扫描物料
        cy.get('body').then(() => {
          // 如果有隐藏输入框，模拟扫描
          cy.get('body').then(($body) => {
            if ($body.find('.hidden-input').length > 0) {
              cy.get('.hidden-input').type(parts.valid[0].scanCode + '{enter}')
              cy.wait(1000)
              
              // 验证扫描结果
              cy.get('body').should('exist')
            }
          })
        })
      })
    })
  })

  describe('数据持久化验证', () => {
    it('应该验证前端操作数据能正确保存到后端', () => {
      cy.fixture('test-data').then((testData) => {
        // 创建测试扫描记录
        const scanRecord = {
          orderNo: testData.orders.valid.orderNo,
          mounterId: testData.orders.valid.machineId,
          smtSide: 'TOP',
          partId: testData.parts.valid[0].partId,
          rollNo: testData.parts.valid[0].rollNo,
          lotNo: testData.parts.valid[0].lotNo,
          operatorId: testData.operators.valid.operatorId,
          scanTime: new Date().toISOString(),
          status: 'OK'
        }
        
        // 通过API提交数据
        cy.apiRequest('POST', '/api/smt/scan-record', scanRecord)
          .then((submitResponse) => {
            cy.log(`Submit response: ${submitResponse.status}`)
            
            if (submitResponse.status === 200 || submitResponse.status === 201) {
              // 验证数据已保存 - 查询刚提交的记录
              cy.apiRequest('GET', `/api/smt/scan-records/${scanRecord.orderNo}`)
                .then((queryResponse) => {
                  cy.log(`Query response: ${queryResponse.status}`)
                  
                  if (queryResponse.status === 200 && queryResponse.body.data) {
                    expect(queryResponse.body.data).to.be.an('array')
                  }
                })
            }
          })
      })
    })
  })

  describe('业务规则验证', () => {
    it('应该验证重复扫描检测', () => {
      cy.fixture('test-data').then((testData) => {
        const scanRecord = {
          orderNo: testData.orders.valid.orderNo,
          mounterId: testData.orders.valid.machineId,
          smtSide: 'TOP',
          partId: testData.parts.valid[0].partId,
          rollNo: testData.parts.valid[0].rollNo,
          lotNo: testData.parts.valid[0].lotNo,
          operatorId: testData.operators.valid.operatorId,
          scanTime: new Date().toISOString()
        }
        
        // 第一次提交
        cy.apiRequest('POST', '/api/smt/scan-record', scanRecord)
          .then((firstResponse) => {
            cy.log(`First scan: ${firstResponse.status}`)
            
            // 立即重复提交相同记录
            cy.apiRequest('POST', '/api/smt/scan-record', scanRecord)
              .then((secondResponse) => {
                cy.log(`Duplicate scan: ${secondResponse.status}`)
                
                // 验证重复检测逻辑
                if (firstResponse.status === 200) {
                  // 如果第一次成功，第二次应该被检测为重复
                  expect([400, 409, 200]).to.include(secondResponse.status)
                }
              })
          })
      })
    })

    it('应该验证无效物料ID检测', () => {
      cy.fixture('test-data').then((testData) => {
        const invalidScanRecord = {
          orderNo: testData.orders.valid.orderNo,
          mounterId: testData.orders.valid.machineId,
          smtSide: 'TOP',
          partId: testData.parts.invalid[0].partId,
          rollNo: testData.parts.invalid[0].rollNo,
          lotNo: testData.parts.invalid[0].lotNo,
          operatorId: testData.operators.valid.operatorId,
          scanTime: new Date().toISOString()
        }
        
        cy.apiRequest('POST', '/api/smt/scan-record', invalidScanRecord)
          .then((response) => {
            cy.log(`Invalid part scan: ${response.status}`)
            
            // 无效物料应该被拒绝
            expect([400, 404, 422]).to.include(response.status)
            
            if (response.body.code) {
              expect(response.body.code).to.not.equal('200')
            }
          })
      })
    })
  })

  describe('性能和负载测试', () => {
    it('应该测试并发API请求', () => {
      cy.fixture('test-data').then((testData) => {
        const requests = []
        
        // 创建多个并发请求
        for (let i = 0; i < 5; i++) {
          requests.push(
            cy.apiRequest('GET', `/api/smt/order/${testData.orders.valid.orderNo}`)
          )
        }
        
        // 验证所有请求都能正常处理
        requests.forEach((request, index) => {
          request.then((response) => {
            cy.log(`Concurrent request ${index + 1}: ${response.status}`)
            expect([200, 404, 500]).to.include(response.status)
          })
        })
      })
    })

    it('应该测试API响应时间', () => {
      cy.fixture('test-data').then((testData) => {
        const startTime = Date.now()
        
        cy.apiRequest('GET', `/api/smt/order/${testData.orders.valid.orderNo}`)
          .then((response) => {
            const endTime = Date.now()
            const responseTime = endTime - startTime
            
            cy.log(`API response time: ${responseTime}ms`)
            
            // 验证响应时间在合理范围内
            expect(responseTime).to.be.lessThan(5000) // 5秒内
          })
      })
    })
  })

  describe('错误处理集成测试', () => {
    it('应该测试网络超时处理', () => {
      // 设置很短的超时时间
      cy.apiRequest('GET', '/api/smt/order/TEST123')
        .then((response) => {
          cy.log(`Timeout test response: ${response.status}`)
          // 验证服务器能够处理请求或返回适当的错误
          expect(response.status).to.be.a('number')
        })
    })

    it('应该测试大量数据处理', () => {
      // 创建大量测试数据
      const largeBatchRecords = []
      for (let i = 0; i < 10; i++) {
        largeBatchRecords.push({
          orderNo: `BATCH${i.toString().padStart(3, '0')}`,
          mounterId: 'M05',
          smtSide: 'TOP',
          partId: `PART${i.toString().padStart(3, '0')}`,
          rollNo: `ROLL${i.toString().padStart(3, '0')}`,
          lotNo: `LOT${i.toString().padStart(3, '0')}`,
          operatorId: 'OP001',
          scanTime: new Date().toISOString()
        })
      }
      
      // 批量提交数据
      cy.apiRequest('POST', '/api/smt/batch-scan-records', largeBatchRecords)
        .then((response) => {
          cy.log(`Batch submission: ${response.status}`)
          
          // 验证批量处理能力
          if (response.status === 200) {
            expect(response.body).to.have.property('code')
          } else {
            // 如果不支持批量提交，也是有效的测试结果
            expect([404, 405, 501]).to.include(response.status)
          }
        })
    })
  })
})